import { getMenulist } from '../api/menu.js'
export const initMenu = async (store) => {
	// 菜单不为空初始化
	if (store.state.menus.length > 0) {
		return
	}
	const { data } = await getMenulist()
	if (data) {
		// 已经格式化好的路由数组
		let fmtRouters = formateRouters(data)
		//添加进路由数组
		// router.addRoutes(fmtRouters)
		//存入vuex
		// router.options.routes.push(fmtRouters[0])
		store.commit('menus', fmtRouters)
	}
}

export const formateRouters = (routers) => {
	let fmtRouters = []
	if (routers) {
		routers.forEach((router) => {
			let { path, component, name, iconCls, children } = router

			// 递归

			if (children && children instanceof Array && children != []) {
				children = formateRouters(children)
			}
			let fmRouters = {
				path: path,
				name: name,
				iconCls: iconCls,
				children: children,
				component: (resolve) => {
					if (component.startsWith('Sys')) {
						require(['@/views/sys/' + component + '.vue'], resolve)
					} else {
						require(['@/views/' + component + '.vue'], resolve)
					}
				},
			}

			fmtRouters.push(fmRouters)
		})
	}

	return fmtRouters
}
